#include "sCRIEditableText.h"
#include "sCREditableText.h"
#include "sFontPreset.h"
#include "sGui.h"

#include <iostream>
#include <iterator>
#include <deque>

namespace sgui
{
namespace inst
{
		
sComponentRectEditableText::~sComponentRectEditableText()
{
	//
}

sComponentRectEditableText::sComponentRectEditableText(const res::sComponentRectText& componentRect, sComponentInstance& instance, s32 id) :
	sComponentRectText(componentRect, instance, id)
{
    //
}
        
void sComponentRectEditableText::getCursorPosition(const sTextCursorPosition& pos, math::sPointf& res_pos, f32& res_height) const
{
    getStrings()[pos.m_line]->getCursorPosition(pos.m_char, res_pos, res_height);
}
        
sTextCursorPosition sComponentRectEditableText::getPositionAt(const math::sPointf& point)
{
    sTextCursorPosition position;
    position.m_line = 0;
    position.m_char = 0;
    
    const std::deque<sTextString*>& lines = getStrings();

    if (!lines.empty())
    {
	    const res::sComponentRectText& m_object = get<res::sComponentRectText>();

		math::sPointf pnt(point - getTextRect().getPosition());

        if (pnt.Y < 0)
        {
            position.m_line = 0;
        }
        else
        {
            if (!lines.empty())
            {
                position.m_line = lines.size() - 1;

                for (u32 i = 0, t = lines.size(); i < t; ++i)
	            {
                    const math::sRectf& rect = lines[i]->getRect();
                    if (pnt.Y >= rect.Y && pnt.Y < rect.Y + rect.H)
                    {
                        position.m_line = i;
                        break;
                    }
	            }
            }
        }

        sTextString* line = lines[position.m_line];

        position.m_char = line->getCharAt(point - line->getRect().getPosition());
    }

	return position;
}

void sComponentRectEditableText::OnHoverGet()
{
    getInstance().setState(CS_HOVER);
}

void sComponentRectEditableText::OnHoverRelease()
{
    getInstance().setState(CS_NORMAL);
}

};
};